function beforeUpload(that, file) {
    that.fileName = file.name
    that.form.key = uuid();
    that.form.token = that.$store.state.global.qiniuToken;
    if (file.name) {
        var temp = file.name.split('.');
        if (temp && temp.length > 0) {
            that.type = temp[temp.length - 1]
        }
    }

};

function handleProgress(that, event, file, fileList) {
    that.loaded = (event.loaded / 1000000).toFixed(2)
    that.fileSize = (event.total / 1000000).toFixed(2)
    that.percent = (event.loaded / event.total * 100).toFixed(2)
};

function handleSuccess(that, response, file, fileList) {
    that.result = '上传成功地址: ' + 'http://static.cyyzjk.com/' + that.form.key;
    that._write2DB(that.type, that.fileName, 'http://static.cyyzjk.com/' + that.form.key, file.size)
};

function handleError(that, error, response, file) {
    var errMsg = error.toString();
    if (errMsg & errMsg.indexOf('token') >= 0) {
        that.result = 'token失效,请点击左上角刷新token，等待token刷新成功后上传';
    } else {
        that.result = error.toString()
    }
};
const IMAGE_FORMATS = ['bmp', 'jpg', 'png', 'tiff', 'gif', 'pcx', 'tga', 'exif', 'fpx', 'svg', 'psd', 'cdr', 'pcd', 'dxf', 'ufo', 'eps', 'ai', 'raw', 'WMF'];
const VIDEO_FORMATS = ['wmv', 'asf', 'asx', 'rm', 'rmvb', 'mpg', 'mpeg', 'mpe', '3gp', 'mov', 'mp4', 'm4v', 'avi', 'dat', 'mkv', 'flv', 'vob']
const AUDIO_FORMATS = ['mp3', 'aac', 'wav', 'wma', 'cda', 'flac', 'm4a', 'mid', 'mka', 'mp2', 'mpa', 'mpc', 'ape', 'ofr', 'ogg', 'ra', 'wv', 'tta', 'ac3', 'dts']

function _isImage(type) {
    var TypeLower = '';
    if (type) {
        var typeLower = type.toLowerCase();
        if (typeLower) {
            if (IMAGE_FORMATS.indexOf(typeLower) >= 0) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    } else {
        return false;
    }
};

function _isVideo(type) {
    var TypeLower = '';
    if (type) {
        var typeLower = type.toLowerCase();
        if (typeLower) {
            if (VIDEO_FORMATS.indexOf(typeLower) >= 0) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    } else {
        return false;
    }
};

function _isAudio(type) {
    var TypeLower = '';
    if (type) {
        var typeLower = type.toLowerCase();
        if (typeLower) {
            if (AUDIO_FORMATS.indexOf(typeLower) >= 0) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    } else {
        return false;
    }
};

function uuid() {
    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
};


function formatterTime(item) {
    var date = new Date(item.time * 1000);
    return date.toLocaleDateString();
};

function formatterSize(item) {
    // console.log(size)
    var b = Number(item.size);
    console.log(b)

    if (b > 1024) {
        var kb = Math.floor((b / 1024) * 100) / 100
        console.log(kb)

        if (kb > 1024) {
            var mb = Math.floor((kb / 1024) * 100) / 100
            console.log(mb)

            if (mb > 1024) {
                var g = Math.floor((mb / 1024) * 100) / 100
                return g + "G";
            }
            return mb + 'MB';
        }
        return kb + 'KB';
    }
    return b + 'B';
};


/**
 * 页码改变的事件
 * 
 * @param {any} currentPage 跳转后页码
 */
function handleCurrentChange(that, currentPage) {
    that.currentPage = currentPage;
    that._getRes();
};

/** 提交表单 */
function submitForm(that, formName) {
    that.$refs[formName].validate((valid) => {
        if (valid) {
            const formData = that[formName]
            that._updateRes(formData);
        } else {
            return false;
        }
    });
};

function checkLevel(that) {
    var user = that.$store.state.user.userinfo;
    return user && user.level == 1;
};

function onDelete(that, res, index) {
    that.$confirm('是否确认删除该资源？', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
    }).then(_ => {
        that._deleteRes(res);
    }).catch((err) => {
        that.$message.error(err);
    });
};

function onEidt(that, item) {
    that.updateFormVisible = true;
    that.resForm = item;
};

// function _getQiniuToken(that) {
//     QiniuApi.getQiniuToken.call(that, data => {
//         that.$store.dispatch('update_qiniu_token', {
//             token: data['token'],
//         });
//     })
// };

const RES_PUBLIC_FIELDS = [{
    info: {
        prop: 'url',
        label: 'url',
        sortable: true
    },
    filter: {
        multiple: false
    },
    style: {
        align: 'center'
    }
}, {
    info: {
        prop: 'name',
        label: '资源名称',
        sortable: true
    },
    filter: {
        multiple: false
    },
    style: {
        width: '120',
        align: 'center'
    }
}, {
    info: {
        prop: 'type',
        label: '资源类型',
        sortable: false
    },
    filter: {
        multiple: false
    },
    style: {
        width: '120',
        align: 'center'
    }
}];
const SIZE_FIELD = {
    info: {
        prop: 'size',
        label: '资源大小',
        sortable: true
    },
    filter: {
        multiple: false
    },
    style: {
        width: '120',
        align: 'center'
    }
};
const TIME_FIELD = {
    info: {
        prop: 'time',
        label: '创建时间',
        sortable: true
    },
    filter: {
        multiple: false
    },
    style: {
        width: '120',
        align: 'center'
    }
};
const REMARK_FIELD = {
    info: {
        prop: 'remark',
        label: '资源备注',
        sortable: false
    },
    filter: {
        multiple: false
    },
    style: {
        width: '120',
        align: 'center'
    }
};
const TABLE_COUNT_DEFAULT = 10;
const tableCount = TABLE_COUNT_DEFAULT;
const layout = "total, prev, pager, next, jumper"; //sizes, prev, pager, next, jumper, ->, total, slot

module.exports = {
    beforeUpload: beforeUpload,
    handleProgress: handleProgress,
    handleSuccess: handleSuccess,
    handleError: handleError,
    // _write2DB: _write2DB,
    _isImage: _isImage,
    _isAudio: _isAudio,
    _isVideo: _isVideo,
    formatterTime: formatterTime,
    formatterSize: formatterSize,
    handleCurrentChange: handleCurrentChange,
    submitForm: submitForm,
    checkLevel: checkLevel,
    onDelete: onDelete,
    onEidt: onEidt,
    resPublicFields: RES_PUBLIC_FIELDS,
    sizeFields: SIZE_FIELD,
    timeFields: TIME_FIELD,
    remarkFields: REMARK_FIELD,
    layout: layout,
    tableCount: tableCount

};